package com.ruima.study.jdk21.jdk19.demo1;

import java.time.Duration;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.stream.IntStream;

/**
 * <p>
 * <p>虚拟线程如何创建</p>
 * <p>
 * <p>Copyright (c) 2024/11/13 11:41, 科大讯飞 All Rights Reserve</p>
 *
 * @author ruima6
 * @version [V1.0]
 */
public class VirtualThreadCreateDemo {
    public static void main(String[] args) throws InterruptedException {
        createFunc1();
        createFunc2();
        createFunc3();
        createFunc4();
    }

    private static void createFunc1() throws InterruptedException {
        //创建任务
        Runnable task = () -> {
            System.out.println("执行任务");
        };

        //创建虚拟线程将任务task传入并启动
        Thread thread = Thread.startVirtualThread(task);

        System.out.println(thread.getName() + "是否为虚拟线程" + thread.isVirtual());

        //主线程睡眠，否则可能看不到控制台的打印
        TimeUnit.SECONDS.sleep(1);
    }

    private static void createFunc2() throws InterruptedException {
        //创建任务
        Runnable task = () -> {
            System.out.println("执行任务2");
        };

        //创建虚拟线程将任务task传入并启动
        Thread thread = Thread.ofVirtual().name("魏建华").start(task);

        System.out.println(thread.getName() + "是否为虚拟线程" + thread.isVirtual());

        //主线程睡眠，否则可能看不到控制台的打印
        TimeUnit.SECONDS.sleep(1);
    }


    private static void createFunc3() throws InterruptedException {
        //创建任务
        Runnable task = () -> {
            System.out.println("执行任务3");
        };

        //创建虚拟线程将任务task传入并启动
        Thread thread = Thread.ofVirtual().name("刘局").unstarted(task);
        thread.start();

        System.out.println(thread.getName() + "是否为虚拟线程" + thread.isVirtual());

        //主线程睡眠，否则可能看不到控制台的打印
        TimeUnit.SECONDS.sleep(1);
    }

    private static void createFunc4(){
        try (ExecutorService executor = Executors.newVirtualThreadPerTaskExecutor()) {
            //向executor中提交100个任务
            IntStream.range(0, 100).forEach(i -> {
                executor.submit(() -> {
                    //睡眠1秒
                    try {
                        Thread.sleep(Duration.ofSeconds(1));
                        System.out.println(i);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                });
            });
        }
    }




}
